package com.microwintech.boardingtreasure.util;

import java.io.*;

/**
 * Created by IntelliJ IDEA.
 * User: Chris.F
 * Date: 2010-9-27
 * Time: 18:55:42
 */
public class IOUtil {
    public static void closeOutputStream(OutputStream out) {
        if (out == null)
            return;
        try {
            out.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void closeInputStream(InputStream in) {
        if (in == null)
            return;
        try {
            in.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void closeWriter(Writer writer) {
        if (writer == null)
            return;
        try {
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void closeReader(Reader reader) {
        if (reader == null)
            return;
        try {
            reader.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static byte[] read(InputStream is) throws IOException {
        return read(is, 1024);
    }

    public static byte[] read(InputStream is, int bufferSize) throws IOException {
        ByteArrayOutputStream bos = null;
        try {
            bos = new ByteArrayOutputStream();
            byte[] buffer = new byte[bufferSize];
            int num = -1;
            while ((num = is.read(buffer)) != -1) {
                bos.write(buffer, 0, num);
            }
            bos.flush();
            return bos.toByteArray();
        } finally {
            closeOutputStream(bos);
        }
    }
}